package com.hjj.homieMatching.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hjj.homieMatching.common.BaseResponse;
import com.hjj.homieMatching.common.ErrorCode;
import com.hjj.homieMatching.common.ResultUtils;
import com.hjj.homieMatching.constant.RedisConstant;
import com.hjj.homieMatching.exception.BusinessException;
import com.hjj.homieMatching.model.domain.User;
import com.hjj.homieMatching.model.request.DeleteRequest;
import com.hjj.homieMatching.model.request.UserEditRequest;
import com.hjj.homieMatching.model.request.UserLoginRequest;
import com.hjj.homieMatching.model.request.UserRegisterRequest;
import com.hjj.homieMatching.model.vo.SignInInfoVO;
import com.hjj.homieMatching.model.vo.UserInfoVO;
import com.hjj.homieMatching.model.vo.UserVO;
import com.hjj.homieMatching.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest, HttpServletRequest request) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.userRegister(request, userRegisterRequest);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "登录请求不能为空");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名或密码不能为空");
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer i = userService.userLogout(request);
        return ResultUtils.success(i);
    }

    /**
     * 获取当前用户登录信息
     *
     * @param request
     * @return safetyuser
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request, HttpServletResponse response) {
        // 记录请求信息用于调试
        log.info("获取当前用户信息, Session ID: {}", request.getSession().getId());
        log.info("Cookie信息: {}", Arrays.toString(request.getCookies()));
        
        User currentUser = userService.getLoginUser(request);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        
        // 设置一个测试Cookie以确认响应是否正常发送Cookie
        Cookie testCookie = new Cookie("testCookie", "testValue");
        testCookie.setPath("/");
        testCookie.setDomain("47.109.146.201");
        testCookie.setMaxAge(3600);
        testCookie.setHttpOnly(false);
        testCookie.setSecure(false);
        response.addCookie(testCookie);
        
        return ResultUtils.success(currentUser);
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        if (userService.getLoginUser(request) == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "你没有管理员权限");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> collect = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(collect);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (userService.getLoginUser(request) == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody UserEditRequest userEditRequest, HttpServletRequest request) {
        // 1.校验参数是否为空
        if (userEditRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2.校验权限
        User loginUser = userService.getLoginUser(request);

        // 3.触发更新
        int result = userService.updateUser(userEditRequest, loginUser);
        return ResultUtils.success(result);
    }

    @GetMapping("/recommend")
    public BaseResponse<List<UserVO>> recommendUsers(long pageSize, long pageNum, HttpServletRequest request) {
        if (pageSize < 0 || pageNum < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<UserVO> userVOS = userService.recommendUsers(pageSize, pageNum, request);
        return ResultUtils.success(userVOS);
    }

    @GetMapping("/search/tags")
    public BaseResponse<List<UserVO>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList,
                                                        HttpServletRequest request) {
        if (userService.getLoginUser(request) == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<UserVO> userList = userService.searchUsersByTags(tagNameList, request);
        return ResultUtils.success(userList);
    }

    /**
     * 推荐最匹配的用户
     *
     * @return
     */
    @GetMapping("/match")
    public BaseResponse<List<UserVO>> matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.matchUsers(num, loginUser));
    }

    /**
     * 搜索附近用户
     */
    @GetMapping("/searchNearby")
    public BaseResponse<List<UserVO>> searchNearby(@RequestParam(defaultValue = "100") int radius, HttpServletRequest request) {
        if (radius <= 0 || radius > 10000) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        User loginUser = userService.getById(user.getId());
        List<UserVO> userVOList = userService.searchNearby(radius, loginUser);
        return ResultUtils.success(userVOList);
    }

//    @GetMapping("/blog/count")
//    public BaseResponse<Long> loginUserBlogCount(HttpServletRequest request) {
//        User loginUser = userService.getLoginUser(request);
//        long userId = loginUser.getId();
//        long count = userService.hasBlogCount(userId);
//        return ResultUtils.success(count);
//    }

    @GetMapping("/follower/count")
    public BaseResponse<Long> loginUserFollowerCount(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        long userId = loginUser.getId();
        long count = userService.hasFollowerCount(userId);
        return ResultUtils.success(count);
    }

    @GetMapping("/info/get")
    public BaseResponse<UserInfoVO> getUserInfo(HttpServletRequest request) {
       UserInfoVO userInfoVO = userService.getUserInfo(request);
       return ResultUtils.success(userInfoVO);
    }

    @GetMapping("/score/rank")
    public BaseResponse<List<User>> getUsersScoreRank() {
        List<User> users = userService.getUsersScoreRank();
        return ResultUtils.success(users);
    }

    @PostMapping("/sign/in")
    public BaseResponse<Boolean> userSigIn(HttpServletRequest request) {
        boolean b = userService.userSigIn(request);
        return ResultUtils.success(b);
    }

    @GetMapping("/sign/in/info/get")
    public BaseResponse<SignInInfoVO> getSignedDates(HttpServletRequest request) {
        SignInInfoVO signInInfoVO = userService.getSignedDates(request);
        return ResultUtils.success(signInInfoVO);
    }

    @GetMapping("/get/id")
    public BaseResponse<UserVO> getUserById(@RequestParam Long id, HttpServletRequest request) {
        if (id == null || id < 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        
        // 记录调试信息 - 当前登录用户的位置信息
        log.info("当前登录用户 ID: {}, 经度: {}, 纬度: {}", 
                loginUser.getId(), loginUser.getLongitude(), loginUser.getDimension());
        
        // 获取目标用户
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        
        // 记录调试信息 - 目标用户的位置信息
        log.info("目标用户 ID: {}, 经度: {}, 纬度: {}", 
                user.getId(), user.getLongitude(), user.getDimension());
        
        user = userService.getSafetyUser(user);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        
        // 计算两个用户之间的距离
        if (loginUser.getLongitude() != null && loginUser.getDimension() != null 
                && user.getLongitude() != null && user.getDimension() != null) {
            String redisUserGeoKey = RedisConstant.USER_GEO_KEY;
            
            // 记录Redis Key信息
            log.info("Redis地理位置Key: {}", redisUserGeoKey);
            
            // 检查Redis中是否存在这两个用户的地理位置数据
            Boolean hasLoginUserGeo = stringRedisTemplate.opsForGeo().geoPos(redisUserGeoKey, String.valueOf(loginUser.getId()))
                    .stream().findFirst().isPresent();
            Boolean hasTargetUserGeo = stringRedisTemplate.opsForGeo().geoPos(redisUserGeoKey, String.valueOf(user.getId()))
                    .stream().findFirst().isPresent();
            
            log.info("Redis中存在登录用户地理位置数据: {}, 目标用户地理位置数据: {}", hasLoginUserGeo, hasTargetUserGeo);
            
            // 如果Redis中缺少地理位置数据，尝试添加
            if (!hasLoginUserGeo) {
                log.info("尝试添加登录用户地理位置数据到Redis");
                stringRedisTemplate.opsForGeo().add(redisUserGeoKey, 
                        new Point(loginUser.getLongitude(), loginUser.getDimension()), 
                        String.valueOf(loginUser.getId()));
            }
            
            if (!hasTargetUserGeo) {
                log.info("尝试添加目标用户地理位置数据到Redis");
                stringRedisTemplate.opsForGeo().add(redisUserGeoKey, 
                        new Point(user.getLongitude(), user.getDimension()), 
                        String.valueOf(user.getId()));
            }
            
            // 计算距离
            Distance distance = stringRedisTemplate.opsForGeo().distance(
                    redisUserGeoKey,
                    String.valueOf(loginUser.getId()),
                    String.valueOf(user.getId()),
                    RedisGeoCommands.DistanceUnit.KILOMETERS
            );
            
            // 设置距离值，处理null情况
            if (distance != null) {
                userVO.setDistance(distance.getValue());
                log.info("用户距离计算: 用户{}到用户{}的距离是{} km", 
                        loginUser.getId(), user.getId(), userVO.getDistance());
            } else {
                userVO.setDistance(0.0);
                log.warn("Redis返回距离为null! 用户{}到用户{}的距离设置为0", loginUser.getId(), user.getId());
            }
        } else {
            // 如果任一用户没有位置信息，设置距离为0
            userVO.setDistance(0.0);
            log.warn("无法计算距离: 用户{}或用户{}缺少位置信息", loginUser.getId(), user.getId());
        }
        
        return ResultUtils.success(userVO);
    }
}
